package 左哥算法.ch16小结构;

import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * https://leetcode.cn/problems/lru-cache/description/
 */
public class LRUCache {

    int capacity;
    Node[] map = new Node[10001];
    LinkedList list = new LinkedList();

    public LRUCache(int capacity) {
        this.capacity = capacity;
    }

    public int get(int key) {
        if (map[key] == null) return -1;
        list.remove(map[key]);
        list.addFirst(map[key]);
        return map[key].v;
    }

    public void put(int key, int value) {
        if (map[key] != null) {
            get(key);
            map[key].v = value;
            return;
        }
        if (list.size >= capacity) {
            Node node = list.popLast();
            map[node.k] = null;
        }
        insert(key, value);
    }

    public void insert(int key, int val) {
        map[key] = new Node(key, val);
        list.addFirst(map[key]);
    }

    static class LinkedList {

        int size;

        Node head, tail;

        public LinkedList() {
            this.head = new Node(-1, -1);
            this.tail = new Node(-1, -1);
            head.next = tail;
            tail.pre = head;
        }

        public void remove(Node o) {
            o.pre.next = o.next;
            o.next.pre = o.pre;
            size--;
        }

        public void addFirst(Node o) {
            o.next = head.next;
            o.pre = head;
            o.next.pre = o;
            o.pre.next = o;
            size++;
        }

        public Node popLast() {
            Node last = tail.pre;
            if (last == head) return null;
            remove(last);
            return last;
        }
    }

    static class Node {
        Node pre, next;
        int k, v;

        public Node(int k, int v) {
            this.k = k;
            this.v = v;
        }
    }

    public static void main(String[] args) {
        LRUCache cache = new LRUCache(2);

        cache.put(1, 1);
        cache.put(2, 2);
        Assert.assertEquals(1, cache.get(1));       // 返回  1
        cache.put(3, 3);    // 该操作会使得密钥 2 作废
        Assert.assertEquals(-1, cache.get(2));      // 返回 -1 (未找到)
        cache.put(4, 4);    // 该操作会使得密钥 1 作废
        Assert.assertEquals(-1, cache.get(1));      // 返回 -1 (未找到)
        Assert.assertEquals(3, cache.get(3));       // 返回  3
        Assert.assertEquals(4, cache.get(4));
    }
}
